package main

import (
	"flag"
	"os"

	"gitee.com/dark.H/go-remote-repl/cli"

	// "log"
	"net"
	"venus"

	log "github.com/sirupsen/logrus"
)

var (
	pem        string
	key        string
	server     string
	host       string
	proxy      string
	address    string
	NouseTls   bool
	cached     bool
	Domain     string
	demoConfig bool
	configFile string
)

func main() {
	// flag.ErrHelp = fmt.Errorf("")
	flag.StringVar(&configFile, "c", "", "load config file")
	flag.BoolVar(&demoConfig, "H", false, "show demo config file ")
	flag.StringVar(&pem, "pem", "", "pem file path")
	flag.StringVar(&key, "pri", "", "private key file path")
	flag.StringVar(&host, "reward", "www.baidu.com", "host rewarding to")
	flag.StringVar(&proxy, "proxy", "", "proxy string set tor:// | socks5://ip:port | ss://uri | ssr://uri | vmess://uri | https://ordered_addresss_which_belong_to_ssr_or_vmess ")
	flag.StringVar(&address, "listen", "", "listen host")
	flag.StringVar(&Domain, "domain", "", "set domain.")
	flag.BoolVar(&NouseTls, "scheme", false, "use 'http' as scheme, default https")
	flag.BoolVar(&cached, "cache", false, "if saved in local tmp")

	// flag.Parse()
	cli.APIParse()
	venus.InitLog()
	// InitLog("/tmp/" + os.Args[0] + ".log")

	if Domain != "" {
		venus.Domain = Domain
	}

	if NouseTls {
		venus.SetDefaultScheme("http")
	}
	if cached {
		venus.UseFileSave = true
	}
	if address != "" {
		venus.SetDefaultListenAddress(address)
	}

	if configFile != "" {
		conf := venus.ReadConf(configFile)
		conf.StartServer()
		os.Exit(0)
	}

	if demoConfig {
		venus.ShowDemo()
		os.Exit(0)
	}

	log.SetLevel(log.DebugLevel)
	tls := venus.ReadFromFileToTlsConfig(pem, key)
	tls.Server = address
	lst, err := tls.WithTlsListener()
	log.WithField("server", tls.Server).WithField("proxy", proxy).WithField("reward to", host).Info(" Start Service")
	relayer := venus.NewRelayer(host, proxy)

	go relayer.Datas.RunInBack()
	if err != nil {
		log.Fatal(err)
	}
	for {
		l, err := lst.Accept()
		if err != nil {
			log.Fatalf("Break ! : %v", err)
			break
		}
		go func(c net.Conn) {
			defer c.Close()
			if err := relayer.Handle(c,nil); err != nil {
				log.Trace(err)
			}
		}(l)
	}
}
